package com.xjd.transport.mock;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WriteSocketClient extends Thread {
	public static Logger log = LoggerFactory.getLogger(WriteSocketClient.class);
	
	InetSocketAddress targetAddress;
	InputStream src;
	boolean success = false;
	boolean failed = false;
	

	public void setTargetAddress(InetSocketAddress targetAddress) {
		this.targetAddress = targetAddress;
	}

	public void setSrc(InputStream src) {
		this.src = src;
	}

	public void run() {
		try {
			serve();
		} catch (IOException e) {
			log.error("server error", e);
			failed = true;
		}
	}
	
	public void serve() throws IOException {
		Socket socket = new Socket();
		socket.connect(targetAddress);
		
		OutputStream out = socket.getOutputStream();
		int i = 0;
		long totall = 0;
		while ((i = src.read()) != -1) {
			out.write(i);
			log.trace("write " + " : " + i + "\t[" + (++totall) + "]");
		}
		success = true;
		
		try {
			socket.close();
		} catch (Exception e) {
			log.error("server error", e);
		}
	}


	public static void main(String[] args) throws UnknownHostException, IOException {
		WriteSocketClient c = new WriteSocketClient();
		c.setTargetAddress(new InetSocketAddress(9090));
		c.serve();
	}

}
